package cloud.keveri.gateway.plugin.call.proxy;

import cloud.keveri.base.KeveriException;
import cloud.keveri.gateway.dto.invoker.ServiceInvoker;
import cloud.keveri.gateway.plugin.api.KeveriPluginChain;
import cloud.keveri.gateway.plugin.api.support.BodyParamUtils;
import cloud.keveri.gateway.plugin.api.support.ParamCheckUtils;
import com.alibaba.fastjson2.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.service.GenericException;
import org.apache.dubbo.rpc.service.GenericService;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Objects;
import java.util.concurrent.CompletableFuture;

import static cloud.keveri.gateway.plugin.api.GatewayPluginErrorCodeConstants.PARAM_NOT_MATCH;
import static cloud.keveri.gateway.plugin.base.ErrorHandler.handlerError;
import static cloud.keveri.gateway.plugin.base.def.Const.ERROR_FLAG;
import static cloud.keveri.gateway.plugin.base.def.Const.RPC_RESULT;
import static cloud.keveri.gateway.plugin.call.def.Const.CLIENT_RESPONSE_RESULT_TYPE;

/**
 * <p>
 * 作者：沈自在
 **/
public class DubboProxyService extends AbstractRpcCacheSupport {
    public Mono<Object> genericInvoker(final String body, ServiceInvoker invoker, final ServerWebExchange exchange)
            throws KeveriException {
        // 1. 获取 Key
        String referenceKey = invoker.getInvokerPath();

        // 2. 获取 Reference Service
        ReferenceConfig<GenericService> reference = get(referenceKey);
        if (StringUtils.isEmpty(reference.getInterface())) {
            invalidate(referenceKey);
            reference = initRefN(invoker);
        }
        GenericService genericService = reference.get();

        // 3. 处理参数
        Pair<String[], Object[]> pair;
        if (StringUtils.isBlank(invoker.getParameterTypes()) || ParamCheckUtils.bodyIsEmpty(body)) {
            pair = new ImmutablePair<>(new String[]{}, new Object[]{});
        } else {
            pair = buildParameter(body, invoker.getParameterTypes());
        }

        // 4. 校验参数是否匹配
        if (pair.getLeft().length != pair.getRight().length) {
            handlerError(exchange, PARAM_NOT_MATCH);
            return Mono.empty();
        }

        // 5. 发起调用
        return Mono.fromFuture(invokeAsync(genericService, invoker.getMethodName(), pair.getLeft(), pair.getRight()).thenApply(ret -> {
            if (Objects.isNull(ret)) {
                ret = "dubbo has not return value!";
            }
            exchange.getAttributes().put(RPC_RESULT, ret);
            exchange.getAttributes().put(CLIENT_RESPONSE_RESULT_TYPE, "success");
            return ret;
        })).onErrorMap(exception -> exception instanceof GenericException ? new KeveriException(((GenericException) exception).getExceptionMessage()) : new KeveriException(exception));
    }

    @SuppressWarnings("all")
    private CompletableFuture<Object> invokeAsync(final GenericService genericService, final String method, final String[] parameterTypes, final Object[] args) throws GenericException {
        //Compatible with asynchronous calls of lower Dubbo versions
        genericService.$invoke(method, parameterTypes, args);
        Object resultFromFuture = RpcContext.getContext().getFuture();
        return resultFromFuture instanceof CompletableFuture ? (CompletableFuture<Object>) resultFromFuture : CompletableFuture.completedFuture(resultFromFuture);
    }

    private Pair<String[], Object[]> buildParameter(String body, String parameterTypes) {
        return BodyParamUtils.buildParameters(body, parameterTypes);
    }
}
